package practice.connectionpool;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 测试超时模式下的数据库连接池
 * 模拟客户端使用过程
 * 
 * 超时机制: 针对资源的系统自我保护机制
 * 
 * threadCnt Total NotGot
 *    10      200    0
 *    20      400    13
 *    30      600    61
 *    40      800    121
 * 
 * @author insight
 * @since 2021/9/9
 */
public class ConnectionPoolTest {
    static ConnectionPool pool = new ConnectionPool(10);
    static CountDownLatch start = new CountDownLatch(1);
    static CountDownLatch end;

    public static void main(String[] args) throws InterruptedException {
        int threadCnt = 40;
        int cnt = 20;
        // 用于暂时停止 main 的执行 等待所有线程结束
        end = new CountDownLatch(threadCnt);
        AtomicInteger got = new AtomicInteger();
        AtomicInteger notGot = new AtomicInteger();

        for (int i = 0; i < threadCnt; i++) {
            new Thread(new ConnectionRunner(cnt, got, notGot),
                    "ConnectionRunner")
                    .start();
        }

        // 用于保证所有线程同时开始
        start.countDown();
        end.await();

        System.out.println("total invoke: " + (threadCnt * cnt));
        System.out.println("Got: " + got.intValue());
        System.out.println("Not Got: " + notGot.intValue());
    }

    static class ConnectionRunner implements Runnable {
        int cnt;
        AtomicInteger get;
        AtomicInteger notGet;

        public ConnectionRunner(int cnt, AtomicInteger get, AtomicInteger notGet) {
            this.cnt = cnt;
            this.get = get;
            this.notGet = notGet;
        }

        @Override
        public void run() {
            try {
                start.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            while (cnt > 0) {
                try {
                    Connection connection = pool.getConnection(1000);
                    if (connection == null) {
                        notGet.incrementAndGet();
                    } else {
                        try {
                            connection.createStatement();
                            connection.commit();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        } finally {
                            get.incrementAndGet();
                            pool.releaseConnection(connection);
                        }
                    } 
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    --cnt;
                }
            }
            
            end.countDown();
        }
    }
    
}